import jwt from 'jsonwebtoken';
import { find } from 'lodash';
import { match } from 'path-to-regexp';

import { jwtSecret } from '../utils';

const whitelist = [
  '/',
  '/user/login',
  '/refresh-token',
];

const grantedList = [
  '/user/login',
  '/user/product-hotels/user/:userId/product/:productId',
];

// eslint-disable-next-line consistent-return
export default function authenticateToken(req, res, next) {
  console.log('-------------------------------------req.url: ', req.url);
  console.log('-------------------------------------req.path: ', req.path);

  // Gather the jwt access token from the request header
  if (whitelist.indexOf(req.path) >= 0) {
    console.log('不需要验证token');
    next();
  } else {
    console.log('需要验证token');
    const matched = find(grantedList, (item) => {
      const routeMatcher = match(item, { decode: decodeURIComponent });
      return routeMatcher(req.path);
    });

    if (!matched) return res.status(403).json({ error: 'Forbidden' });

    const authHeader = req.headers.authorization;
    const token = authHeader && authHeader.split(' ')[1];

    jwt.verify(token, jwtSecret, (err, user) => {
      if (err) {
        res.sendStatus(401);
      } else {
        req.user = user;
        // console.log(user);
        next(); // pass the execution off to whatever request the client intended
      }
    });
  }
}
